package com.apes.framework.plugin.soe.core.service.impl;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.Model;
import com.apes.framework.plugin.soe.core.service.TaskService;
import com.apes.framework.plugin.soe.metadata.SceneFlow;
import com.apes.framework.util.JpaUtil;
import com.apes.framework.util.MapUtil;
import org.springframework.stereotype.Component;

/**
 * 功能：任务服务实现类
 *
 * @author xul
 * @create 2018-09-25 16:46
 */
@Component
public class TaskServiceImpl extends DomainService implements TaskService {

    /**
     * 执行任务
     *
     * @param sceneFlow
     * @param model
     */
    @Override
    public Object complete(SceneFlow sceneFlow, Model model) {
        Object result = model;

        /**出站 outbound 执行**/
        if (sceneFlow.getOutbound() != null) {
            result = invoke(sceneFlow.getOutbound().getId(), MapUtil.mapped(model));
            if (result == null) {
                throw new RuntimeException("出站接口：" + sceneFlow.getOutbound() + " 返回值错误不允许为空");
            }
        }

        if (sceneFlow.getInbound() != null) {
            Class<?> clazz = null;
            if (sceneFlow.getTargetBusinessType() != null) {
                clazz = JpaUtil.getDomainClass(sceneFlow.getTargetBusinessType().getId());
                if (!Model.class.isAssignableFrom(clazz)) {
                    throw new RuntimeException("凭证类型（目标）：" + sceneFlow.getTargetBusinessType() + " 错误");
                }
            }

//            /**数据转换**/
//            if (Map.class.isAssignableFrom(result.getClass())) {
//                /**扩展目标对象：注入场景**/
//                if (!((Map) result).containsKey("scene")) {
//                    ((Map) result).put("scene", MapUtil.mapper("id", model.getScene().getId()));
//                }
//
//                /**扩展目标对象：行级数据过滤**/
//                if (clazz != null) {
//
//                }
//
//            } else if (clazz != null && clazz.isAssignableFrom(result.getClass())) {
//                /**扩展目标对象：注入场景**/
//                ((Model) result).setScene(model.getScene());
//
//                /**扩展目标对象：行级数据过滤**/
//                if (clazz != null) {
//
//                }
//            } else {
//                throw new RuntimeException("出站接口：" + sceneFlow.getOutbound() + " 返回值错误");
//            }

            /**入站 inbound执行**/
            result = invoke(sceneFlow.getInbound().getId(),  MapUtil.mapped(result));
        }
        return result;
    }

}
